<template>
	<view>
		<!-- <free-nav-bar title="下游服务商注册" showBack></free-nav-bar> -->
		<u-form :model="form" ref="uForm">
			<free-nav-title title="账号信息"></free-nav-title>
			<view class="pl-3 pr-3">
				<u-form-item required label-width="150" label="登录账号" prop="username">
					<u-input class="mr-3 " v-model="form.username" placeholder="建议以企业名称作为登录账号" />
				</u-form-item>
				<u-form-item label-width="150" label="登录密码" prop="password">
					<u-input class="mr-3 " :password-icon="true" type="password" v-model="form.password" placeholder="请输入密码" />
				</u-form-item>
			</view>
			<free-nav-title title="注册信息"></free-nav-title>
			<view class="pl-3 pr-3">
				<u-form-item required label-width="180" label="上传营业执照" prop="uploadSuccess">
					<u-upload ref="uUpload" :max-size="4 * 1024 * 1024" :form-data="{'biz':'license'}"
						@on-success="uploadSuccess" :action="getUploadUrl()" max-count="1"></u-upload>
					<view class="font-12 text-999999 pl-1">图片限制不能超过4MB</view>
				</u-form-item>

				<u-form-item required label-width="150" label="企业名称" prop="enterpriseName">
					<u-input class="mr-3 " :disabled="true" v-model="form.enterpriseName" placeholder="请输入企业名称" />
				</u-form-item>
				<u-form-item required required label-width="150" label="手机号码" prop="phone">
					<u-input class="mr-3 " maxlength="11" v-model="form.phone" placeholder="请输入手机号码" />
				</u-form-item>

				<u-form-item required label-width="150" label="验证码" prop="phoneCaptcha">
					<u-input class="mr-3 " v-model="form.phoneCaptcha" placeholder="请输入验证码" />
					<u-button size="mini" slot="right" type="warning" @click="getCode">{{codeText}}</u-button>
				</u-form-item>
				<u-toast ref="uToast"></u-toast>
				<u-verification-code :seconds="seconds" @end="end" @start="start" ref="uCode"
					@change="codeChange"></u-verification-code>

				<u-button class="mt-6" type="success" @click="sumin">提交</u-button>
			</view>
		</u-form>
	</view>
</template>

<script>
	import $H from '@/common/free-lib/request.js';
	import freeNavBar from "@/components/free-ui/free-nav-bar.vue"
	import freeNavTitle from "@/components/free-ui/free-nav-title.vue"
	export default {
		components: {
			freeNavBar,
			freeNavTitle,
		},
		data() {
			return {
				codeText: '',
				seconds: 60,
				form: {
					username: "",
					password: "",
					enterpriseName: "",
					phone: "",
					phoneCaptcha: "",
					businessLicense: "",
					unifiedCreditCode: "",
					legalRepresentative: ""
				},
				rules: {
					username: [{
						required: true,
						message: '登录账号不能为空',
						trigger: ['change', 'blur'],
					}],
					enterpriseName: [{
						required: true,
						message: '请输入企业名称',
						trigger: ['change', 'blur'],
					}],
					phone: [{
							required: true,
							message: '请输入手机号码',
							trigger: ['change', 'blur'],
						},
						{
							validator: (rule, value, callback) => {
								const reg = /^[0-9]*$/; // 只允许输入数字
								if (!reg.test(value)) {
									callback(new Error('请输入数字'));
								} else {
									callback();
								}
							},
							trigger: ['change', 'blur'],
						}
					],

					phoneCaptcha: [{
							required: true,
							message: '请输入验证码',
							trigger: ['change', 'blur'],
						},
						{
							validator: (rule, value, callback) => {
								const reg = /^[0-9]*$/; // 只允许输入数字
								if (!reg.test(value)) {
									callback(new Error('请输入数字'));
								} else {
									callback();
								}
							},
							trigger: ['change', 'blur'],
						}
					],
					password: [{
					        required: true,
					        message: '请输入密码',
					        trigger: ['change', 'blur'],
					    },
					    {
					        validator: (rule, value, callback) => {
					            // 正则表达式，要求密码包含英文、数字、特殊字符中的至少2种组成，不少于6位
					            const reg = /^(?=.*[a-zA-Z])(?=.*\d|.*[\W_])[A-Za-z\d\W_]{6,}$/;
					            if (!reg.test(value)) {
					                callback(new Error('密码必须包含英文、数字、特殊字符中的至少二种，且长度不少于6位'));
					            } else {
					                callback();
					            }
					        },
					        trigger: ['change', 'blur'],
					    }
					]

				},
			}
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		methods: {
			codeChange(text) {
				this.codeText = text;
			},
			validatePhoneNumber(phoneNumber) {
				var regex = /^1\d{10}$/;
				return regex.test(phoneNumber);
			},

			getCode() {
				if (this.getCodeisWaiting) {
					return;
				}
				// 验证手机号码是否为空
				if (!this.form.phone) {
					uni.showToast({
						title: "请输入手机号码",
						icon: 'none'
					});
					return;
				}
				// 隐藏键盘
				uni.hideKeyboard();
				this.getCodeText = "发送中...";
				this.getCodeisWaiting = true;
				let o = {
					phone: this.form.phone
				};

				// 发送请求获取验证码
				$H.get('/brand/user/visitor/down/sendSms', o, {
						token: false
					})
					.then(res => {
						if (!res.success || res.code != 200) {
							uni.showToast({
								title: res.message || '获取验证码失败',
								icon: 'error'
							});
							return;
						}
						if (this.$refs.uCode.canGetCode) {
							if (!this.validatePhoneNumber(this.form.phone)) {
								uni.showToast({
									title: "手机号码格式错误",
									icon: "error"
								});
								return;
							}
							uni.showLoading({
								title: '正在获取验证码'
							});
							setTimeout(() => {
								uni.hideLoading();
								this.$refs.uCode.start();
							}, 2000);
						} else {
							this.$u.toast('倒计时结束后再发送');
						}
					})
					.catch(error => {
						uni.showToast({
							title: "网络错误，请稍后再试",
							icon: 'none'
						});
					});
			},
			end() {
				this.$u.toast('倒计时结束');
				this.getCodeisWaiting = false;
				this.codeText = '重新获取';
			},
			start() {
				this.$u.toast('倒计时开始');
			},
			getUploadUrl(url) {
				return $H.getFullUrl('/sys/common/visitor/upload');
			},

			uploadSuccess(response) {
				if (response.code === 0) {
					if (response.result === null) {
						uni.showToast({
							title: '上传失败，请上传正确的营业执照',
							icon: 'none',
							duration: 4000
						});
						this.clearImage();
						return;
					}
					this.form.basePhoto = [{
						url: response.message,
						message: response.message,
						enterpriseName: response.result
					}];
					this.form.enterpriseName = response.result;
				} else {
					uni.showToast({
						title: response.success === true ? '上传成功' : '上传失败',
						icon: 'none'
					});
				}
			},
			clearImage() {
				this.$refs.uUpload.lists = [];
			},

			sumin() {
				this.$refs.uForm.validate(valid => {
					if (valid) {
						let files = [];

						files = this.$refs.uUpload.lists.filter(val => {
							return val.progress == 100;
						})
						if (files.length == 0) {
							uni.showToast({
								title: '请上传文件',
								icon: 'none'
							});
							return;
						}
						let o = {
							...this.form,
							businessLicense: files[0].response.message
						};
						$H.post('/brand/user/visitor/down/add', o, {
								token: false
							})
							.then(res => {

								if (res.code === 200) {
									uni.showToast({
										title: res.message,
										icon: 'none',
										duration: 4000,
									});
									setTimeout(() => {
										uni.navigateBack({
											delta: 1
										});
									}, 4000);
								} else {
									uni.showToast({
										title: res.message,
										icon: 'none',
									});
								}
							})
							.catch(error => {
								uni.showToast({
									title: "网络错误，请稍后再试",
									icon: 'none'
								});
							});
					} else {
						uni.showToast({
							title: "请完整填写表单",
							icon: 'none'
						});
					}
				});
			}
		}
	}
</script>

<style>

</style>